import Http from "../http/http.js"
var QQMapWX = require('./qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWX({
  key: 'EFJBZ-NTGW4-TJZUZ-XJGTU-KXXKH-BUBMP'
});
var oss = {
  OSSAccessKeyId: '',
  dir: '',
  host: '',
  policy: '',
  signature: ''
}
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/
function formatTimeTwo(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
// 登录信息

function loginreport(){
   var pars={
     address:'',
     brand:'',
     lat:'',
     lng:'',
     model:'',
     system:'',
     version:''
   }
  // 获取经纬度
  wx.getLocation({
    type: 'gcj02',
    success: function (res) {
      console.log(res)
      pars.lat = res.latitude
      pars.lng = res.longitude
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: res.latitude,
          longitude: res.longitude
        },
        success: function (re) {
          pars.address = re.result.address
          setTimeout(function () {
            Http.postdata('/rest/tsa/restTerminalInfoApi/saveTerminalLoginRecord', pars).then((res) => {
              console.log(res)
            })
          }, 3000)
        },
        fail: function (error) {
          console.error(error);
        },
      })
    },
    fail: function (res) {
      console.log(res)
    }
  }),
  // 获取系统信息
    wx.getSystemInfo({
      success(res) {
        pars.model = res.model
        pars.brand = res.brand
        pars.system = res.system
        pars.version = res.version
      }
    })
}

function withData(param) {
  return param < 10 ? '0' + param : '' + param;
}
function getLoopArray(start, end) {
  var start = start || 0;
  var end = end || 1;
  var array = [];
  for (var i = start; i <= end; i++) {
    array.push(withData(i));
  }
  return array;
}
function getMonthDay(year, month) {
  var flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0), array = null;

  switch (month) {
    case '01':
    case '03':
    case '05':
    case '07':
    case '08':
    case '10':
    case '12':
      array = getLoopArray(1, 31)
      break;
    case '04':
    case '06':
    case '09':
    case '11':
      array = getLoopArray(1, 30)
      break;
    case '02':
      array = flag ? getLoopArray(1, 29) : getLoopArray(1, 28)
      break;
    default:
      array = '月份格式不正确，请重新输入！'
  }
  return array;
}
function getNewDateArry() {
  // 当前时间的处理
  var newDate = new Date();
  var year = withData(newDate.getFullYear()),
    mont = withData(newDate.getMonth() + 1),
    date = withData(newDate.getDate()),
    hour = withData(newDate.getHours()),
    minu = withData(newDate.getMinutes()),
    seco = withData(newDate.getSeconds());

  return [year, mont, date, hour, minu, seco];
}
function dateTimePicker(startYear, endYear, date) {
  // 返回默认显示的数组和联动数组的声明
  var dateTime = [], dateTimeArray = [[], [], [], [], [], []];
  var start = startYear || 1978;
  var end = endYear || 2100;
  // 默认开始显示数据
  var defaultDate = date ? [...date.split(' ')[0].split('-'), ...date.split(' ')[1].split(':')] : getNewDateArry();
  // 处理联动列表数据
  /*年月日 时分秒*/
  dateTimeArray[0] = getLoopArray(start, end);
  dateTimeArray[1] = getLoopArray(1, 12);
  dateTimeArray[2] = getMonthDay(defaultDate[0], defaultDate[1]);
  dateTimeArray[3] = getLoopArray(0, 23);
  dateTimeArray[4] = getLoopArray(0, 59);
  dateTimeArray[5] = getLoopArray(0, 59);

  dateTimeArray.forEach((current, index) => {
    dateTime.push(current.indexOf(defaultDate[index]));
  });

  return {
    dateTimeArray: dateTimeArray,
    dateTime: dateTime
  }
}
// 去除字符串前后空格
function trim(str) { //删除左右两端的空格
  return str.replace(/(^\s*)|(\s*$)/g, "");
}
// 数据字典
function getValues(type){
  setTimeout(function(){
    Http.getdata('/rest/tsa/dictDataRestApiController/getValuesByCode?type=' + type).then((res) => {
      var result = []
      result = res.data.data
      console.log(result)
      return result
    })
  },1000)
}

// 获取oss
// 获取阿里上传凭证
function getoss(){
  Http.getdata('/rest/tsa/credentialCall/getOssSignature', { filePath: 'image/' }).then((res) => {
    if (res.data.code == 0) {
          oss.OSSAccessKeyId=res.data.data.accessId,
          oss.dir =res.data.data.dir,
          oss.host =res.data.data.host,
          oss.policy =res.data.data.policy,
          oss.signature =res.data.data.signature
      }
      console.log(res.data.data)
    })
}

// 上传图片
function upload(type,mode,code,path){
  
  var _that = this
  var photo=''
  if(type=='ycjtb'){
    photo ='album'
  }
  var timestamp3 = Date.now()
  return new Promise(function (resolve, reject) {
    getoss()
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera',photo],
      success(res) {
        wx.showLoading({
          title: '上传中',
          duration: 1000,
          mask: true
        })
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        let imgName = tempFilePaths[0].lastIndexOf(".");
        let imgNameLength = tempFilePaths[0].length;
        let fileFormat = tempFilePaths[0].substring(imgName + 1, imgNameLength);
        // console.log(wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], "base64"))
        var result = ''
        var licepic=''
        wx.uploadFile({
          url: oss.host, // 仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            OSSAccessKeyId: oss.OSSAccessKeyId,
            policy: oss.policy,
            signature: oss.signature,
            key: oss.dir + type + timestamp3 + code+ '.' + fileFormat,
            success_action_status: "200"
          },
          success(re) {
            if (re.statusCode == 200) {
              wx.hideLoading()
              wx.showToast({
                title: "上传成功",
                icon: 'success',
                duration: 1000,
                mask: true
              })
              var obj={
                result: oss.host + '/' + oss.dir + type + timestamp3 + code+'.' + fileFormat,
                temp: res.tempFilePaths[0]
              }
              // licepic = wx.getFileSystemManager().readFileSync(obj.temp, "base64")
              // _that.bdai(licepic)
              resolve(obj)
            }else{
              wx.hideLoading()
              wx.showToast({
                title: "上传失败,请重新上传",
                icon: 'success',
                duration: 1000,
                mask:true
              })
            }
          },
          fail:function(){
            wx.hideLoading()
            wx.showToast({
              title: "上传失败,请重新上传",
              icon: 'none',
              duration: 1500,
              mask: true
            })
          }
        })
      }
    })
  })
}
// 任意时间差
function dateCompare(beginDate, endDate) {
  var d1 = new Date(beginDate.replace(/\-/g, '/'))
  var d2 = new Date(endDate.replace(/\-/g, '/'))
  if (beginDate != '' && endDate != '') return d2 - d1
}
// 检查微信版本
function checkUpdateVersion() {
  //创建 UpdateManager 实例
  const updateManager = wx.getUpdateManager();
  //检测版本更新
  updateManager.onCheckForUpdate(function (res) {
    console.log(res)
    // 请求完新版本信息的回调
    if (res.hasUpdate) {
      //监听小程序有版本更新事件
      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          confirmColor:'#FF3941',
          showCancel:false,
          success(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate();
            }
          }
        })
      })

      updateManager.onUpdateFailed(function (res) {
        console.log(res)
        // 新版本下载失败
        wx.showModal({
          title: '当前版本为最新版本',
          content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开',
        })
      })
    }
  })
}
// 获取省市区，街道地址
function map(){
  var _that = this;
  return new Promise(function (resolve, reject) {
    wx.chooseLocation({
      success(res) {
        var totaladress = res.address
        var subaddress = totaladress.substring(0, totaladress.lastIndexOf('区') + 1) || totaladress.substring(0, totaladress.lastIndexOf('市') + 1) || totaladress.substring(0, totaladress.indexOf('县') + 1)
        var endaddress = totaladress.replace(subaddress, '')
        console.log(totaladress.replace(subaddress, ''))
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude,
          },
          success:function(re){
            var obj={
              obj1:res,
              obj2:re.result

            }
            obj.obj1.address = endaddress
            resolve(obj)
            
          },
          fail: function (error) {
            console.error(error);
          },
        })
      },
      fail: function () {
        wx.showToast({
          title: '定位失败,请重试',
          mask: true,
          icon: 'none'
        })
      }
    })
  })
}

module.exports = {
  formatTime: formatTime,
  formatTimeTwo: formatTimeTwo,
  loginreport: loginreport,
  dateTimePicker: dateTimePicker,
  getMonthDay: getMonthDay,
  trim: trim,
  getValues: getValues,
  getoss: getoss,
  upload: upload,
  dateCompare: dateCompare,
  checkUpdateVersion: checkUpdateVersion,
  map: map
}